package com.xse.security.web;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 动态权限修改示例
 * 假设当前你的权限只有 ROLE_USER。那么按照上面的代码：
 * 1、直接访问 /vip/test 路径将会得到403的Response；
 * 2、访问 /vip 获取 ROLE_VIP 授权，再访问 /vip/test 即可得到正确的Response。
 *
 * @author xieshue
 * @date 2018\2\5 0005
 */
@RestController
public class VipController {
    /**
     * 使用@Secured注解需要开启@EnableGlobalMethodSecurity(securedEnabled = true)
     * ,@Secured("ROLE_VIP")  需要ROLE_VIP权限可访问
     *
     * @return
     */
    @GetMapping("/vip/test")
    @Secured("ROLE_VIP")
    public String vipPath() {
        // 得到当前的认证信息
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return "仅 ROLE_VIP 可看";
    }

    @GetMapping("/vip")
    public boolean updateToVIP() {
        // 得到当前的认证信息
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        //  生成当前的所有授权
        List<GrantedAuthority> updatedAuthorities = new ArrayList<>(auth.getAuthorities());
        // 添加 ROLE_VIP 授权
        updatedAuthorities.add(new SimpleGrantedAuthority("ROLE_VIP"));
        // 生成新的认证信息
        Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), updatedAuthorities);
        // 重置认证信息
        SecurityContextHolder.getContext().setAuthentication(newAuth);
        return true;
    }
}
